﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;

namespace T.FAS.Runtime.MF.Activities.Helper
{
    internal class HttpHelper
    {
        public static async Task<string> SendPostRequestAsync(string url, string jsonContent, string apiKey)
        {
            using var httpClient = new HttpClient();
            using var content = new StringContent(jsonContent, Encoding.UTF8, "application/json");

            // 设置请求头
            httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", apiKey);
            httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            try
            {
                // 发送请求并获取响应
                  HttpResponseMessage response = httpClient.PostAsync(url, content).GetAwaiter().GetResult();
                //HttpResponseMessage response =await httpClient.PostAsync(url, content);

                // 处理响应
                if (response.IsSuccessStatusCode)
                {
                    return await response.Content.ReadAsStringAsync();
                }
                else
                {
                    throw new Exception( $"请求失败: {response.StatusCode}");
                }
            }
            catch (Exception e)
            {

                throw;
            }
           
        }
        public static string PostUrl(string sgUrl, string SgServiceId, string param, string contentType = "application/json",
       Dictionary<string, string> headerTable = null)
        {
            string responseText = string.Empty;
            try
            {
                sgUrl = sgUrl.Replace("{0}", SgServiceId);
                //构造WebRequest
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(sgUrl);
                request.Method = "post";
                //request.ContentType = "application/x-www-form-urlencoded";
                request.ContentType = contentType;
                request.Timeout = 300000;
                request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; rv:19.0) Gecko/20100101 Firefox/19.0"; //模拟火狐
                byte[] postdatabyte = Encoding.UTF8.GetBytes(param);
                request.ContentLength = postdatabyte.Length;
                request.AllowAutoRedirect = false;

                if (headerTable != null)
                {
                    foreach (var item in headerTable)
                    {
                        request.Headers.Add(item.Key, item.Value);
                    }
                }


                Stream stream;
                stream = request.GetRequestStream();
                stream.Write(postdatabyte, 0, postdatabyte.Length); //设置请求主体的内容
                stream.Close();

                //请求响应
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Stream responseStream = response.GetResponseStream();
                StreamReader sr = new StreamReader(responseStream);
                responseText = sr.ReadToEnd();
            }
            catch (WebException e)
            {
                if (e.Response != null)
                {
                    Stream responseStream = e.Response.GetResponseStream();
                    StreamReader sr = new StreamReader(responseStream);
                    responseText = sr.ReadToEnd();
                    throw e;
                }
            }

            return responseText;
        }
    }
}
